package com.ihr360.expr.function;



import com.ihr360.expr.ExprException;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprFunction;
import com.ihr360.expr.core.IExprFunction;

import java.util.LinkedHashSet;
import java.util.Set;

public class FunctionManager implements IFunctionProvider
{
    private FunctionMap functionMap;
    private Set<IFunctionProvider> providers = new LinkedHashSet();

    public FunctionManager() {
        this(false);
    }

    public FunctionManager(boolean caseSensitive) {
        functionMap = new FunctionMap(caseSensitive);
        providers.add(functionMap);
    }

    public void add(String name, IExprFunction function) {
        functionMap.add(name, function);
    }

    public void add(IFunctionProvider provider) {
        providers.add(provider);
    }

    @Override
    public Expr evaluate(IEvaluationContext context, ExprFunction function)
            throws ExprException {
        for (IFunctionProvider p : providers) {
            if (p.hasFunction(function))
                return p.evaluate(context, function);
        }
        return null;
    }
    @Override
    public boolean hasFunction(ExprFunction function) {
        for (IFunctionProvider p : providers) {
            if (p.hasFunction(function))
                return true;
        }

        return false;
    }
}
